#include <AceButton.h>
using namespace ace_button;

#include "cmds.h"

#define STRS_LEN(strs) (sizeof(strs)/sizeof(int))
#define Send_Comds(cmds) send_cmds(cmds, STRS_LEN(cmds));

// The pin number attached to the button.
const int BUTTON_PIN = 6;
const int BUTTON2_PIN = 7;
const int BUTTON_PIN_STOP = 8;

AceButton button(BUTTON_PIN);
AceButton button2(BUTTON2_PIN);

bool cmds_state = true;

char terminatorChar = 'ok\n';    // 定义终止字符为‘T’

void handleEvent(AceButton*, uint8_t, uint8_t);

bool get_cmds_state() {
  return cmds_state;
}

void set_cmds_state(bool s) {
  cmds_state = s;
}

void send_cmds(char *cmds[], int len) {
  for (int i = 0; i < len; i++) {
    if (!get_cmds_state())
      break;
    Serial.println(cmds[i]);
    Serial.readStringUntil(terminatorChar);
  }

  set_cmds_state(true);
}

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  Serial.setTimeout(10*1000);
//  Serial.println("setup");
//  Serial.println(sizeof(Get_Bottle_Cmds));
//  Serial.println(sizeof(Home_Cmds));
//  send_cmds(Home_Cmds, STRS_LEN(Home_Cmds));
//  Serial.println(sizeof(Get_Right_Cmds));
  // Button uses the built-in pull up register.
  pinMode(BUTTON_PIN, INPUT_PULLUP);
  pinMode(BUTTON2_PIN, INPUT_PULLUP);
    // Configure the ButtonConfig with the event handler, and enable all higher
  // level events.
  ButtonConfig* buttonConfig = button.getButtonConfig();
  buttonConfig->setEventHandler(handleEvent);
  buttonConfig->setFeature(ButtonConfig::kFeatureClick);
  buttonConfig->setFeature(ButtonConfig::kFeatureDoubleClick);
  buttonConfig->setFeature(ButtonConfig::kFeatureLongPress);
  buttonConfig->setFeature(ButtonConfig::kFeatureRepeatPress);

//  Send_Comds(Home_Cmds);
}

void loop() {
  // put your main code here, to run repeatedly:
  button.check();
  button2.check();
}

// The event handler for the button.
void handleEvent(AceButton* button, uint8_t eventType,
    uint8_t buttonState) {

  // Print out a message for all events.
//  Serial.print(F("handleEvent(): eventType: "));
//  Serial.print(eventType);
//  Serial.print(F("; buttonState: "));
//  Serial.println(buttonState);

  // Control the LED only for the Pressed and Released events.
  // Notice that if the MCU is rebooted while the button is pressed down, no
  // event is triggered and the LED remains off.
  switch (eventType) {
    case AceButton::kEventPressed:
//      digitalWrite(LED_PIN, LED_ON);
      break;
    case AceButton::kEventReleased:
      if (button->getPin() == BUTTON_PIN) {
        Send_Comds(Home_Cmds);
      }
      if (button->getPin() == BUTTON2_PIN) {
        Send_Comds(Get_Right_Cmds);
      }
      if (button->getPin() == BUTTON_PIN_STOP) {
        set_cmds_state(false);
      }
      
      break;
  }
}

